package aspirecn.project3.service.impl;

import aspirecn.project3.config.OSSConfig;
import aspirecn.project3.service.FileService;
import aspirecn.project3.util.CommonUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * packageName aspirecn.project3.service.impl
 *
 * @author 邵一宸
 * @version JDK 17
 * @className FileServiceImpl
 * @date 2024/7/19
 * @description TODO
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Autowired
    OSSConfig ossConfig;

    //上传普通图片
    @Override
    public String uploadImg(MultipartFile file, String rootFolder) {
        String bucketname=ossConfig.getBucketName();
        String endpoint=ossConfig.getEndpoint();
        String accessKeyId=ossConfig.getAccessKeyId();
        String accessKeySecret=ossConfig.getAccessKeySecret();
        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();

        //JDK8的日期格式 文件切割使用 此处不需要
//        LocalDateTime ldt=LocalDateTime.now();
//        DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy/MM/dd");

        //拼装路径
//        String folder=dtf.format(ldt);
        String fileName= CommonUtil.generateUUID();
        String extension=originalFilename.substring(originalFilename.lastIndexOf("."));
//        String newFileName="user/"+folder+"/"+fileName+extension;
//        String newFileName=rootFolder+"/"+folder+"/"+fileName+extension;
        String newFileName=rootFolder+"/"+fileName+extension;

        try {
            ossClient.putObject(bucketname,newFileName,file.getInputStream());
            String imgUrl="https://"+bucketname+"."+endpoint+"/"+newFileName;
            return imgUrl;
        }catch (IOException e){
            log.error("文件上传失败:{}",e);
        }finally {
            ossClient.shutdown();
        }
        return null;
    }
}